#!/usr/bin/env node
/* eslint-env node */
/* eslint no-console: "off" */

const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const _ = require('underscore');
const chalk = require('chalk');
const {csvParse} = require('d3-dsv');
const {queue} = require('d3-queue');
const request = require('request');

const pluginDirectory = fs.existsSync('../../plugins') ? '../../plugins' : path.resolve(__dirname, '../plugins');

const config = yaml.safeLoad(fs.existsSync('./config.yaml') ? fs.readFileSync('./config.yaml') : fs.readFileSync('../../config.yaml'));


if (!config.translation || !config.translation.core) {
    console.error(chalk.bold.red('Error!'), chalk.yellowBright('You need to set up the translation spreadsheets in config.yaml!'));
    process.exit(-1);
}

if (config.translation) {
    queue(3)
        .defer(getSheet, config.translation.core)
        .defer(getSheet, config.translation.plugins)
        .defer(getSheet, config.translation.chart)
        .await((err, core, plugins, chart) => {
            if (err) return console.error(err);
            // write core locales/*.json
            writeLocales(core, './locale', config.languages);

            var chartTranslations = _.indexBy(chart, 'plugin');
            var chartSrc = _.groupBy(chart, 'plugin');

            _.each(_.groupBy(plugins, 'plugin'), (src, k) => {
                var languages = config.languages;

                if (!_.isEmpty(chartTranslations[k]) && (k === 'themes' || k === 'd3-maps')) {
                    _.each(_.groupBy(chart, 'plugin'), (c, id) => {
                        if (id === k) {
                            src = src.concat(c);
                        }
                    });

                    var locales = config.plugins['chart-locale-select'].locales.split(",")
                    locales.forEach((el, i) => {
                        locales[i] = { id: el.split("|")[0] };
                    });
                    languages = locales;
                }

                if (k) {
                    if (fs.existsSync(`${pluginDirectory}/${k}`)) {
                        writeLocales(src, `${pluginDirectory}/${k}/locale`, languages);
                    } else {
                        console.log(chalk.yellowBright.bold(' ⚇ '), 'ignoring missing plugin', chalk.bold(k));
                    }
                }
            });

            delete chartSrc.themes;
            delete chartSrc['d3-maps'];


            _.each(chartSrc, (rows, key) => {
                if (key) {
                    const locale = {};
                    rows.forEach(row => {
                        const key = row.key;
                        delete row.key;
                        delete row.plugin;
                        locale[key] = row;
                    })
                    fs.writeFileSync(`${pluginDirectory}/${key}/locale/chart-translations.json`, JSON.stringify(locale, null, 4));
                }
            })

            // console.log(chartTranslations);

            // fs.writeFileSync(sheets[0].dest.replace('.csv', '.json'), JSON.stringify(d, null, 3));
            // fs.unlinkSync(sheets[0].dest);
            console.log('Done.');
        });
}

function getSheet(url, callback) {
    request(url, (err, res, body) => {
        if (err) return console.error(err);
        callback(null, csvParse(body));
    });
}

function writeLocales(src, path, languages) {
    if (!fs.existsSync(path)) fs.mkdirSync(path);
    var err = false;
    languages.forEach((lang) => {
        const f = `${path}/${lang.id.replace('-','_')}.json`;
        try {
            fs.accessSync(f, fs.constants.R_OK | fs.constants.W_OK);
        } catch (e) {
            console.error(chalk.red(' ✖ '), 'no permission to write', f);
            err = true;
        }
        const locale = {};
        src.forEach((row) => {
            if (row.key) locale[row.key] = row[lang.id];
        });
        fs.writeFileSync(f, JSON.stringify(locale, null, 2));
    });
    if (!err) console.log(chalk.green(' ✔ ')+' updated translations for', chalk.bold(src[0].plugin || 'core'));
}
